package com.muchfish;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 使用Reactor可以简化下面的操作
 */
public class CompletableFutureExample {

    public static void main(String[] args) {
        // 创建一个CompletableFuture对象，并使用runAsync方法执行异步任务
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            // 异步任务的逻辑
            System.out.println("Async task is running...");
            // 模拟耗时操作
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 当异步任务完成时，执行回调函数
        future.thenRun(() -> System.out.println("Async task completed."));

        // 使用supplyAsync执行有返回值的异步任务
        CompletableFuture<String> futureWithResult = CompletableFuture.supplyAsync(() -> {
            // 异步任务的逻辑
            System.out.println("Async task with result is running...");
            // 模拟耗时操作
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Result of async task";
        });

        // 当有返回值的异步任务完成时，执行回调函数并获取结果
        try {
            String result = futureWithResult.get();
            System.out.println("Async task with result completed. Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

